/* 
 * Copyright (C) 2014 Krzysztof Troska <elleander86 at gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package anidbjclient;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Map;

/**
 * Handles files and directories knows what to do.
 * @author Krzysztof Troska <elleander86 at gmail.com>
 */
public class Episode {
    
    private static final Database db = AnidbJClientGUI.DB;
    
    private static final ConfigManager cm = new ConfigManager();
    
    /**
     * Returns true if file should be checked. first we check 
     * if FORCE_CHECK is passed 
     * next we check if file is in files to add with valid fid next
     * extension from ConfigManager, 
     * next if file is realy video
     * last if file is in other_files db
     * @param path path to a file we want to check  
     * @param FORCE_CHECK if true we don't check if file is in checked files DB
     * @return true if file is video and not checked
     */
    public static boolean checkFile(Path path, final boolean FORCE_CHECK) {
        try {
            if(FORCE_CHECK)
                return true;
            if(db.getFilesToAddFid(path) > 0)
                return false;
            String extension = path.getFileName().toString();
            extension = extension.substring(extension.lastIndexOf(' ') + 1);
            /** */
            if(!cm.compereExtensions(extension) && Files.probeContentType(path).startsWith("video")) {
                if(db.checkOtherFiles(path)) {
                    System.out.println("File already checked, skipping.");
                    return false;
                } else
                    return true;
            } else
                return false;
        } catch (NullPointerException e) {
            return false;
        } catch (IOException e) {
            System.err.println("Can't read from file");
            return false;
        }
    }
    
    /**
     * Moves episode into proper place look {@link #makePath(java.nio.file.Path, java.lang.String, makePath())}
     * @param path path to a file we want to move
     * @param fid fid of episode to move
     * @param dbconn Database connection
     * @return true on success
     */
    public static boolean moveFile(Path path, int fid, Database dbconn) {
        String[] columns = {"anime.name AS name", "anime.anime_type AS anime_type", "anime.adult AS adult"};
        String database = "anime, files WHERE anime.aid = files.aid AND files.fid = " + fid;
        Map<String, List<Object>> animeInfo = dbconn.getDatabaseInfo(columns, database);
        String animeName = changeName(animeInfo.get("name").get(0).toString());
        /** making of a path */
        Path dest = Paths.get(cm.getAnimePath().toString());
        dest = makePath(dest, (String)animeInfo.get("anime_type").get(0), (boolean)animeInfo.get("adult").get(0));
        dest = Paths.get(dest.toString(), animeName);
        dest.toFile().mkdirs();
        /** for last we add file name we don't want to change it. */
        dest = Paths.get(dest.toString(), path.getFileName().toString());
        try {
            /** 
             * We move the file and update path, if file did not moved 
             * then exception is thrown and path in db is not updated.
             */
            Files.move(path, dest, StandardCopyOption.REPLACE_EXISTING);
            dbconn.updateEpisodePath(dest, fid);
            return true;
        } catch (IOException e) {
            System.err.format("Can't move file: %s, massage: %s /n", path.getFileName(), e.getMessage());
            return false;
        }
    }
    
    /**
     * Moves episode into proper place look {@link #makePath(java.nio.file.Path, java.lang.String, makePath())}
     * @param path path to a file we want to move
     * @param fid fid of episode to move
     * @return true on success
     */
    public static boolean moveFile(Path path, int fid) {
        return moveFile(path, fid, db);
    }

    /**
     * Changes name so it wont be refused by OS path
     * @param name to be changed
     * @return changed name
     */
    private static String changeName(String name) {
        String[][] replacements = {{"<", ""}, 
        {">", ""}, {"/", "-"}, {"\\", "/"}, {":", "-"}, 
        {"*", ""}, {"?", "."}, {"\"", "'"}, {"|", ""}};
        for(String[] replacement: replacements) {
            name = name.replace(replacement[0], replacement[1]);
        }
        name = name.trim();
        while(name.matches(".*\\.+$"))
            name = name.substring(0, name.length()-1);
        return name;
    }

    /**
     * Cretes path for a file to be moved
     * @param path path to the file to be moved
     * @param type anime type 
     * @param adult boolean if anime 18+
     * @return path to destination without file name
     */
    private static Path makePath(Path path, String type, boolean adult) {
        if(adult)
            return Paths.get(path.toString(), "H");
        if(type.matches("TV Series"))
            return path;
        else
            return Paths.get(path.toString(), type);
    }
}